﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace TC.Vacation.Spider.Core.Iocp
{
    /// <summary>
    /// 异步IOCP池
    /// </summary>
    internal class SocketAsyncEventArgsPool
    {
        /// <summary>
        /// 一个后进先出的队列
        /// </summary>
        Stack<SocketAsyncEventArgs> m_pool;

        /// <summary>
        /// 根据参数初始化对象池，并且设立池的大小
        /// </summary>
        /// <param name="capacity">对象池的最大容量</param>
        internal SocketAsyncEventArgsPool(int capacity)
        {
            m_pool = new Stack<SocketAsyncEventArgs>(capacity);
        }

        /// <summary>
        /// 将SocketAsyncEventArgs对象放回池中
        /// </summary>
        /// <param name="item"></param>
        internal void Push(SocketAsyncEventArgs item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("Items不能为 Null");
            }
            lock (m_pool)
            {
                m_pool.Push(item);
            }
        }

        /// <summary>
        /// 从池中取出一个SocketAsyncEventArgs对象
        /// </summary>
        /// <param name="item"></param>
        internal SocketAsyncEventArgs Pop()
        {
            lock (m_pool)
            {
                return m_pool.Pop();
            }
        }

        /// <summary>
        /// 池中SocketAsyncEventArgs的个数
        /// </summary>
        internal int Count
        {
            get
            {
                return m_pool.Count;
            }
        }

        /// <summary>
        /// 获取连接池中的套接字对象
        /// </summary>
        /// <value>
        /// The socket.
        /// </value>
        internal Stack<SocketAsyncEventArgs> Socket
        {
            get
            {
                return m_pool;
            }
        }

        /// <summary>
        /// 清空集合
        /// </summary>
        internal void Clear()
        {
            m_pool.Clear();
        }
    }
}
